package org.zp.handler;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zp.dto.AddAdmin;
import org.zp.dto.AdminEdit;
import org.zp.pojo.AddressInfo;
import org.zp.pojo.AdminInfo;
import org.zp.pojo.RoleInfo;
import org.zp.service.AddressService;
import org.zp.service.AdminInfoService;
import org.zp.service.AdminInfoServiceImpl;
import org.zp.service.AdminLogInfoService;
import org.zp.service.NetWorkInfoService;
import org.zp.service.RoleInfoService;
import org.zp.util.Ajax;
import org.zp.util.Security;
import org.zp.util.ValiAdmindate;
import org.zp.util.Validate;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
public class AdminHandler {
	@Resource
	private AdminInfoService a;
	@Resource
	private RoleInfoService r;
	@Resource
	private NetWorkInfoService n;
	@Resource
	private AddressService address;
	@Resource
	private AdminLogInfoService log;
	
	private String url = "人员列表";
	/**
	 * 后台登录
	 * 
	 * @param name
	 * @param pwd
	 * @param code
	 * @param req
	 * @param resp
	 * @param session
	 */
	@PostMapping("login.act")
	public void adminLogin(String name, String pwd, String code, HttpServletRequest req, HttpServletResponse resp,
			HttpSession session) {
		ValiAdmindate validate = new ValiAdmindate();
//	在validate类的基础上利用Ajax类的代码优化
		System.out.println(name + "---" + pwd + "---" + code);
		if (!validate.checkUserName(name)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		// 验证码判断
		String sessonCode = (String) req.getSession().getAttribute("captcha");
		System.out.println("验证码2:" + sessonCode);
		if (null == sessonCode || null == code || !sessonCode.equalsIgnoreCase(code)) {
			Ajax.error(resp, "验证码错误或没输入", 10001);
			return;
		}

		System.out.println(name + "---" + pwd + "---" + code);
		AdminInfo admin = a.mybatisLogin(name, pwd);
		// 登录失败
		if (admin == null) {
			Ajax.error(resp, "该用户不存在", 1000);
			return;
		}


		// 响应数据
		Ajax.success(resp, "date", "main");

		// 登录成功：
		// 把用户名，用户id 存入session
		req.getSession().setAttribute("admin", admin);
	}


/**
 * 管理员管控多条件查询
 * @param name
 * @param role
 * @param start
 * @param end
 * @param req
 * @param resp
 */
	@GetMapping("getAdminlist.act")
	public void getAdminlist(String startpage, String limitpage, String name, String role, String start, String end,
			HttpServletRequest req, HttpServletResponse resp) {
		Integer startpagee = Integer.parseInt(startpage);
		Integer limitpagee = Integer.parseInt(limitpage);
		System.out.println("管理员管控多条件查询startpage:" + startpage);
		System.out.println("管理员管控多条件查询limitpage:" + limitpage);

		Long rolee = (long) Integer.parseInt(role);

		System.out.println(name);
		System.out.println(role);
		System.out.println(start);
		System.out.println(end);

		if (name.equals("")) {
			name = null;
		}
		if (rolee == -1 || rolee == 0) {
			rolee = null;
		}
		if (start.equals("")) {
			start = null;
		}
		if (end.equals("")) {
			end = null;
		}
		if (start != null && end != null) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 日期格式处理
			try {
				Date star = df.parse(start);
				Date endd = df.parse(end);
				if (star.getTime() > endd.getTime()) {// 比较时间的大小
					Ajax.error(resp, "时间有误", 10001);
					return;
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		List<AdminInfo> list = a.selectadmin(startpagee, limitpagee, name, rolee, start, end);
		PageInfo<AdminInfo> pageInfo = new PageInfo<AdminInfo>(list);
		Integer count = (int) pageInfo.getTotal();
		System.out.println("管理员管控多条件查询count:" + count);
		Ajax.success(resp, "list", "count", list, count);
	}

	/**
	 * 修改管理员状态
	 * 
	 * @param status
	 * @param uid
	 * @param req
	 * @param resp
	 */
	@PostMapping("adminEdit.act")
	public void adminEdit(String status, String uid, HttpServletRequest req, HttpServletResponse resp) {
		int Uid = 0;

		try {
			Uid = Integer.parseInt(uid);
		} catch (NumberFormatException e) {
			Ajax.error(resp, "id错误");
			e.printStackTrace();
			return;
		}

		// 初始化选择器的值
		int iStatus = 0;

		try {
			iStatus = Integer.parseInt(status);
		} catch (NumberFormatException e) {
			Ajax.error(resp, "状态错误", 10000);
			e.printStackTrace();
			return;
		}
		Integer index = a.updateAdminState(Uid, iStatus);

		System.out.println("修改结果:" + index);
		if (index > 0) {
			Ajax.success(resp);
			System.out.println("修改成功");
			AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid = admin.getAdminId();
			Integer cid = 3;//此为修改的操作id
			Integer logs = log.addlog(aid,cid,url);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		} else {
			Ajax.error(resp, "修改失败", 10001);
			System.out.println("修改失败");
		}
	}

	/**
	 * 对管理员删除
	 * 
	 * @param uid
	 * @param req
	 * @param resp
	 */
	@PostMapping("adminDel.act")
	public void deleteAdmin(String uid, HttpServletRequest req, HttpServletResponse resp) {
		int Uid = 0;
		try {
			Uid = Integer.parseInt(uid);
		} catch (NumberFormatException e) {
			Ajax.error(resp, "用户id不正确", 10000);
		}
		if (Uid <= 0) {
			Ajax.error(resp, "用户id不正确", 10000);
			return;
		}

		Integer index = a.deleteAdmin(Uid);
		if (index > 0) {
			Ajax.success(resp);
			System.out.println("删除成功");
			AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid = admin.getAdminId();
			Integer cid = 2;//此为删的操作id
			Integer logs = log.addlog(aid,cid,url);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		} else {
			Ajax.error(resp, "删除失败", 10001);
			System.out.println("删除失败");
		}

	}

	/**
	 * 管理员重置密码
	 * 
	 * @param uid
	 * @param req
	 * @param resp
	 */
	@PostMapping("adminIdNewPwd.act")
	public void adminIdNewPwd(String uid, HttpServletRequest req, HttpServletResponse resp) {
		int Uid = 0;
		try {
			Uid = Integer.parseInt(uid);
		} catch (NumberFormatException e) {
			Ajax.error(resp, "用户id不正确", 10000);
		}
		if (Uid <= 0) {
			Ajax.error(resp, "用户id不正确", 10000);
			return;
		}

		Integer index = a.newAdminpwd(Uid);
		if (index > 0) {
			Ajax.success(resp);
			System.out.println("重置成功");
			AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid = admin.getAdminId();
			Integer cid = 3;//此为修改的操作id
			Integer logs = log.addlog(aid,cid,url);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		} else {
			Ajax.error(resp, "重置失败", 10001);
			System.out.println("重置失败");
		}
	}
	/**
	 * 获得省的集合
	 * @param req
	 * @param resp
	 */
	@GetMapping("getAdminaddressone.act")
	public void getaddressone(HttpServletRequest req, HttpServletResponse resp) {
		List<AddressInfo> list = address.getaddressone();
		Ajax.success(resp, "list", list);
	}
	/**
	 * 获得市的集合
	 * @param fid
	 * @param req
	 * @param resp
	 */
	@GetMapping("getAdminaddressTow.act")
	public void getaddressTow(String fid,HttpServletRequest req, HttpServletResponse resp) {
		Integer Fid = Integer.parseInt(fid);
		List<AddressInfo> list = address.getaddressTow(Fid);
		Ajax.success(resp, "list", list);
	}
	/**
	 * 获得区/县集合
	 * @param fid
	 * @param req
	 * @param resp
	 */
	@GetMapping("getAdminaddressThree.act")
	public void getaddressThree(String fid,HttpServletRequest req, HttpServletResponse resp) {
		Integer Fid = Integer.parseInt(fid);
		List<AddressInfo> list = address.getaddressTow(Fid);
		Ajax.success(resp, "list", list);
	}
	/**
	 * 管理员添加
	 * 
	 * @param admin
	 * @param pwd
	 * @param cpwd
	 * @param role
	 * @param req
	 * @param resp
	 */
	@PostMapping("addAdmin.act")
	public void addAdmin(AddAdmin dto, HttpServletRequest req,
			HttpServletResponse resp) {
		String account = dto.getAccount();
		String admin = dto.getAdmin();
		String pwd = dto.getPwd();
		String cpwd = dto.getCpwd();
		String role = dto.getRole();
		Integer one = Integer.parseInt(dto.getAddressOne());
		Integer two = Integer.parseInt(dto.getAddressTwo());
		Integer three = Integer.parseInt(dto.getAddressThree());
		ValiAdmindate validate = new ValiAdmindate();
		Validate va = new Validate();
		if (!va.checkUserName(account)) {
			Ajax.error(resp, va.getError(), 10000);
			return;
		}
		if (!validate.checkUserName(admin)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		if (!va.checkPassword(pwd)) {
			Ajax.error(resp, va.getError(), 10000);
			return;
		}
		if (cpwd.equals("") || cpwd == null) {
			Ajax.error(resp, "请输入确认的密码", 10000);
			return;
		}
		if (!pwd.equals(cpwd)) {
			Ajax.error(resp, "密码不相同", 10002);
			return;
		}

		Long rolee = (long) Integer.parseInt(role);

		if (rolee == 0) {
			Ajax.error(resp, "请选择角色", 10002);
			return;
		}
		
		if (one==0||two==0||three==0) {
			Ajax.error(resp, "请补充完整寄件人地址信息");
			return;
		}
		
		

		AdminInfo sa = new AdminInfo();
		sa.setAdminName(admin);
		sa.setAdminPwd(pwd);
		sa.setRoleId(rolee);
		sa.setAdminAccount(account);
		
		String count = sa.getAdminAccount();
		String pwdd = sa.getAdminPwd();
	try {
		AdminInfo admin2 = a.mybatisLogin(count, pwdd);
		if (!admin2.getAdminAccount().equals("")||admin2.getAdminAccount()!=null) {
			Ajax.error(resp, "添加失败已存在相同账号", 10001);
			return;
		}
	} catch (Exception e) {
		Integer index = a.addAdmin(sa);
		if (index > 0) {
			Ajax.success(resp);
			System.out.println("添加成功");
			//添加对该管理员进行添加网点
			//查询这个新增的对象的id
			AdminInfo ainfo = a.checkAdminInfo(account, pwd);
			Long aid = ainfo.getAdminId();
			//对该id进行网点添加
			Integer x = n.addAdminNetwork(aid,three);
			if (x > 0) {
				System.out.println("添加网点成功");
				return;
			} else {
				System.out.println("添加网点失败");
			}
			AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid1 = admin1.getAdminId();
			Integer cid = 1;//此为增的操作id
			Integer logs = log.addlog(aid1,cid,url);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		} else {
			Ajax.error(resp, "添加失败", 10001);
			System.out.println("添加失败");
		}
	}	
		

		
		

	}

	/**
	 * 欢迎xxx
	 * 
	 * @param req
	 * @param resp
	 */
	@GetMapping("getAdminName.act")
	public void getUsername(HttpServletRequest req, HttpServletResponse resp) {
		AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
		Long aid = admin.getAdminId();
		AdminInfo aInfo = a.getAdminByAid(aid);
		String adminname = aInfo.getAdminName();
		System.out.println("欢迎" + adminname);
		Ajax.success(resp, "adminname", adminname);
	}
/**
 * 管理人员修改
 * @param dto
 * @param req
 * @param resp
 */
	@PostMapping("adminEditdate.act")
	public void adminEdit(AdminEdit dto, HttpServletRequest req, HttpServletResponse resp) {
		AdminInfo admin = (AdminInfo) req.getSession().getAttribute("admin");
		Long aid = admin.getAdminId();
		String aName = dto.getaName();
		String aPwd = dto.getaPwd();
		String cPwd = dto.getcPwd();
		String uAccount = dto.getuAccount();
		ValiAdmindate validate = new ValiAdmindate();
		if (!validate.checkContent(aName)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		if (!validate.checkContent(aPwd)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		if (!validate.checkContent(cPwd)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		if (!validate.checkContent(uAccount)) {
			Ajax.error(resp, validate.getError(), 10000);
			return;
		}
		if (!aPwd.equals(cPwd)) {
			Ajax.error(resp, "密码不相同", 10002);
			return;
		}
		if (aName.equals(admin.getAdminName())) {
			Ajax.error(resp, "和之前名称相同", 10002);
			return;
		}

		List<AdminInfo> list = a.showAdmin();
		for (int i = 0; i < list.size(); i++) {
			String aNames = list.get(i).getAdminName();
			if (aName.equals(aNames)) {
				Ajax.error(resp, "和其他用户名称相同", 10002);
				return;
			}
		}
		Integer index = a.updateAdmindate(aid, aName, aPwd, uAccount);
		if (index > 0) {
			Ajax.success(resp);
			System.out.println("修改成功");
			AdminInfo admin1 = (AdminInfo) req.getSession().getAttribute("admin");
			Long aid1 = admin1.getAdminId();
			Integer cid = 3;//此为修改的操作id
			Integer logs = log.addlog(aid1,cid,url);
			if (logs>0) {
				System.out.println("加入日志成功");
			}else {
				System.out.println("加入日志失败");
				return;
			}
			return;
		} else {
			Ajax.error(resp, "修改失败", 10001);
			System.out.println("修改失败");
			return;
		}

	}

}
